'''
Author        zzx
Date          2022-08-10 11:06:30
LastEditTime  2022-09-20 17:56:56
LastEditors   zzx
Description   功能描述
'''
import importlib
import os

from flask import Blueprint, make_response, json, current_app
from flask_restx import Api

from app.extensions.utils.schemas import CommonSchema, PageBaseSchema


api_v1 = Blueprint("api", __name__, url_prefix="/api/v1")

# swagger文档
authorizations = {
    'apikey': {
        'type': 'apiKey',
        'in': 'header',
        'name': 'authorization'
    }

}

# 若doc_path=False，则不显示swagger文档
docs_path = os.getenv('DOCS_PATH', '/docs')

api = Api(api_v1, version="1.0", title="iHcm 简历解析", description="iHcm 简历解析API文档",
          doc=docs_path, authorizations=authorizations, security='apikey')


# 注册通用Model
api.models[CommonSchema.name] = CommonSchema
api.models[PageBaseSchema.name] = PageBaseSchema


# 自定义异常抛出到框架统一处理
@api.errorhandler(Exception)
def api_error(e):
    raise e


# 自定义输出数据格式
@api.representation('application/json')
def output_json(data, code, headers=None):
    """Makes a Flask response with a JSON encoded body"""

    settings = current_app.config.get("RESTX_JSON", {})

    # If we're in debug mode, and the indent is not set, we set it to a
    # reasonable value here.  Note that this won't override any existing value
    # that was set.
    if current_app.debug:
        settings.setdefault("indent", 4)

    # always end the json dumps with a new line
    # see https://github.com/mitsuhiko/flask/pull/1262
    dumped = data
    if isinstance(data, dict):
        dumped = json.dumps(data, **settings) + "\n"

    resp = make_response(dumped, code)
    resp.headers.extend(headers or {})
    return resp


modules = [
    'v1.user', 'v1.permission', 'v1.system_logs', 'v1.upload',
    'v1.dict_data', 'v1.company', 'v1.resume'
]

# 注册模块
for module in modules:
    imp_module = importlib.import_module('app.modules.{}'.format(module))
    configure_api = getattr(imp_module, 'configure_api')
    configure_api(api)

# # 注册web界面模块
# for module_name in ("web.authentication", "web.home"):
#     module = importlib.import_module("app.{}.routes".format(module_name))
#     current_app.register_blueprint(module.blueprint)
